﻿using Furion.VirtualFileServer;
using ST.Torch.WebApi.Application.System.Dtos;
using ST.Torch.WebApi.Core.Extensions;
using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ST.Torch.WebApi.Application.System.Services
{
    /// <summary>
    /// 文件系统
    /// </summary>
    public class FileService : ITransient
    {
        private readonly IFileProvider _physicalFileProvider;
        //private readonly IFileProvider _embeddedFileProvider;

        private IHttpContextAccessor _httpContextAccessor;
        //public  string rootPath = @"E:\yiwei\WorkGit\WebAdminPro\FileService";
        public string rootPath = App.Configuration["SysInfo:FileServiceUrl"];



        public FileService(Func<FileProviderTypes, object, IFileProvider> fileProviderResolve
            , IHttpContextAccessor httpContextAccessor)
        {
            // 解析物理文件系统
            _physicalFileProvider = fileProviderResolve(FileProviderTypes.Physical, rootPath);
            // 解析嵌入资源文件系统
            //_embeddedFileProvider = fileProviderResolve(FileProviderTypes.Embedded, Assembly.GetEntryAssembly());

            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<string> ReadFileContent(string filePath)
        {
            byte[] buffer;
            using (Stream readStream = _physicalFileProvider.GetFileInfo(filePath).CreateReadStream())
            {
                buffer = new byte[readStream.Length];
                await readStream.ReadAsync(buffer.AsMemory(0, buffer.Length));
            }
            // 读取文件内容
            var content = Encoding.UTF8.GetString(buffer);
            return content;
        }
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<byte[]> ReadFileByte(string filePath)
        {
            byte[] buffer;
            var fileInfo = _physicalFileProvider.GetFileInfo(filePath);
            if (fileInfo.Exists)
            {
                using (Stream readStream = fileInfo.CreateReadStream())
                {
                    buffer = new byte[readStream.Length];
                    await readStream.ReadAsync(buffer.AsMemory(0, buffer.Length));
                }
            }
            else
            {
                return null;
            }

            return buffer;
        }
        /// <summary>
        /// 获取文件目录内容
        /// </summary>
        /// <param name="rootPath"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public List<FileMenu> GetFileMenu(string rootPath, string order, string sort)
        {
            if (rootPath == null)
            {
                rootPath = "";
            }
            if (!rootPath.StartsWith("/"))
            {
                rootPath = "/" + rootPath;
            }
            if (sort == null)
            {
                sort = "Desc";
            }
            if (order == null)
            {
                order = "UpdateTime";
            }
            List<FileMenu> fliemenus = new List<FileMenu>();
            var fileinfos = _physicalFileProvider.GetDirectoryContents(rootPath);
            foreach (var fileinfo in fileinfos)
            {
                FileMenu fliemenu = new FileMenu();
                fliemenu.IsDirectory = fileinfo.IsDirectory;
                fliemenu.Name = fileinfo.Name;
                fliemenu.Length = fileinfo.Length.ToString() + "KB";
                fliemenu.UpdateTime = fileinfo.LastModified;
                string rootUrl = rootPath + "/" + fileinfo.Name;
                if (rootPath == "/")
                {
                    rootUrl = "/" + fileinfo.Name;
                }
                string hosturl = _httpContextAccessor.HttpContext.Request.Scheme + "://" + _httpContextAccessor.HttpContext.Request.Host.ToString() + "/";
                string url = HttpUtility.UrlEncode(rootUrl, Encoding.UTF8);
                fliemenu.Url = url;
                fliemenu.DownloadUrl = hosturl + "api/File/Attachment/" + url;
                if (fileinfo.Name.ToUpper().EndsWith(".BMP")
                    || fileinfo.Name.ToUpper().EndsWith(".JPG")
                    || fileinfo.Name.ToUpper().EndsWith(".JPEG")
                    || fileinfo.Name.ToUpper().EndsWith(".PNG")
                    || fileinfo.Name.ToUpper().EndsWith(".GIF")

                    )
                {

                    fliemenu.Thumbnail = fliemenu.DownloadUrl;
                }
                if (fileinfo.IsDirectory)
                {

                    // 这里递归。。。
                    fliemenu.Data = GetFileMenu(rootPath + fileinfo.Name + "/", order, sort);
                }
                fliemenus.Add(fliemenu);
            }

            return fliemenus.AsQueryable().SetQueryableOrder(order, sort).ToList();
        }

        /// <summary>
        /// 删除文件-文件夹
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public void DeleteFile(string filePath)
        {
            //string path = rootPath + HttpUtility.UrlEncode(filePath, Encoding.UTF8);
            string path = HttpUtility.UrlDecode(rootPath + filePath, Encoding.UTF8);

            var info = _physicalFileProvider.GetFileInfo(path);


            if (Directory.Exists(path))
                Directory.Delete(path, true);
            //删除文件
            if (File.Exists(path))
                File.Delete(path);

            //if (info.IsDirectory)
            //{
            //    if (Directory.Exists(path))
            //        Directory.Delete(path, true);

            //}
            //else
            //{   //删除文件
            //    if (File.Exists(path))
            //        File.Delete(path);

            //}



        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public void CreateDirectory(string filePath)
        {
            if (!filePath.StartsWith("/"))
            {
                filePath = "/" + filePath;
            }
            string path = rootPath + HttpUtility.UrlDecode(filePath, Encoding.UTF8);

            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="flieName">文件名称</param>
        /// <param name="Context">写入内容</param>
        /// <returns></returns>
        public void CreateFile(string filePath, string flieName, string Context)
        {
            filePath = rootPath + filePath;
            string path = filePath + flieName;
            if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);

            if (!File.Exists(path))
            {
                File.Delete(path);
            }
            File.Create(path).Close();//判断文件是否存在，创建txt文件后需要close，否则会出现文件占用情况
            StreamWriter sw = new StreamWriter(path, true, Encoding.Default);//第一个参数代表路径，第二个参数表示文件是否覆盖还是在原有文件基础上添加，第三个参数代表编码格式
            sw.WriteLine(Context);
            sw.Flush();
            sw.Close();


        }

        ///// <summary>
        ///// 读取文件内容
        ///// </summary>
        ///// <returns></returns>
        //public string GetRootPath()
        //{
        //    return rootPath;
        //}

    }
}
